package Admin;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import GroupClass.ConnectRMI;
import Project_etow.EtowInterface;

public class Account extends javax.swing.JDialog {

    ConnectRMI connectRMI = new ConnectRMI();
    private int                     row;
    private String                  acccountedit1;
    private int                     dem, x1, x2, dem2;
    private javax.swing.JButton     btexit;
    private javax.swing.JButton     btdelete;
    private javax.swing.JButton     btedit;
    private javax.swing.JButton     btinsert;
    private javax.swing.JButton     btreset;
    private javax.swing.JButton     btseach;
    private javax.swing.JButton     btbillpayment;
    private javax.swing.JComboBox   cbbsex;
    private javax.swing.JButton     btview;
    private javax.swing.JLabel      lbcompanyname;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable      tbdulieu;
    private javax.swing.JTextField  txtaddress;
    private javax.swing.JTextField  txtage;
    private javax.swing.JTextField  txtcmnd;
    private javax.swing.JTextField  txtcompanyname;
    private javax.swing.JTextField  txtemail;
    private javax.swing.JTextField  txtloginname;
    private javax.swing.JTextField  txtname;
    private javax.swing.JButton     btregistry;
    private javax.swing.JLabel      lbloginname;
    private String                  click1, click2, click3, click4, click5, click6, click7, click8, click9, click10;
    private static String           a1, a2, a3, a4, a5, a6, a7, a8, a9, a10;
    private DefaultTableModel       dtm;

    public String getAcccountedit1() {
        return acccountedit1;
    }

    public void setAcccountedit1(String acccountedit1) {
        this.acccountedit1 = acccountedit1;
    }

    public Account(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

    }

    public void SeachTable() {
        if (txtcompanyname.getText().length() > 0 && txtloginname.getText().length() == 0) {
            x1 = tbdulieu.getRowCount();
            dem = 0;
            for (int i = 0; i < x1; i++) {
                if (tbdulieu.getValueAt(i, 3).toString().equals(txtcompanyname.getText())) {
                    dem += 1;
                    String login = tbdulieu.getValueAt(i, 1).toString();
                    String name = tbdulieu.getValueAt(i, 2).toString();
                    String companyname = tbdulieu.getValueAt(i, 3).toString();
                    String birthday = tbdulieu.getValueAt(i, 4).toString();
                    String sex = tbdulieu.getValueAt(i, 5).toString();
                    String cmnd = tbdulieu.getValueAt(i, 6).toString();
                    String address = tbdulieu.getValueAt(i, 7).toString();
                    String phone = tbdulieu.getValueAt(i, 8).toString();
                    String email = tbdulieu.getValueAt(i, 9).toString();
                    String id = tbdulieu.getValueAt(i, 10).toString();
                    dtm.addRow(new Object[] { new Boolean(false), login, name, companyname, birthday, sex, cmnd,
                            address, phone, email, id });
                }

            }

            for (int i = 0; i < tbdulieu.getRowCount(); i++) {
                while (tbdulieu.getRowCount() != dem) {
                    dtm.removeRow(0);
                }
            }
            txtcompanyname.setText("");
            txtloginname.setText("");
        } else if (txtloginname.getText().length() > 0 && txtcompanyname.getText().length() == 0) {
            x2 = tbdulieu.getRowCount();
            dem2 = 0;
            for (int i = 0; i < x2; i++) {
                if (tbdulieu.getValueAt(i, 2).toString().equals(txtloginname.getText())) {
                    dem2 += 1;
                    String login = tbdulieu.getValueAt(i, 1).toString();
                    String name = tbdulieu.getValueAt(i, 2).toString();
                    String companyname = tbdulieu.getValueAt(i, 3).toString();
                    String birthday = tbdulieu.getValueAt(i, 4).toString();
                    String sex = tbdulieu.getValueAt(i, 5).toString();
                    String cmnd = tbdulieu.getValueAt(i, 6).toString();
                    String address = tbdulieu.getValueAt(i, 7).toString();
                    String phone = tbdulieu.getValueAt(i, 8).toString();
                    String email = tbdulieu.getValueAt(i, 9).toString();
                    String id = tbdulieu.getValueAt(i, 10).toString();
                    dtm.addRow(new Object[] { new Boolean(false), login, name, companyname, birthday, sex, cmnd,
                            address, phone, email, id });
                }
            }
            for (int i = 0; i < tbdulieu.getRowCount(); i++) {
                while (tbdulieu.getRowCount() != dem2) {
                    dtm.removeRow(0);
                }
            }
            txtcompanyname.setText("");
            txtloginname.setText("");
        } else if (txtcompanyname.getText().length() > 0 && txtloginname.getText().length() > 0) {
            x1 = tbdulieu.getRowCount();
            dem = 0;
            for (int i = 0; i < x1; i++) {
                if (tbdulieu.getValueAt(i, 3).toString().equals(txtcompanyname.getText())
                        && tbdulieu.getValueAt(i, 2).toString().equals(txtloginname.getText())) {
                    dem += 1;
                    String login = tbdulieu.getValueAt(i, 1).toString();
                    String name = tbdulieu.getValueAt(i, 2).toString();
                    String companyname = tbdulieu.getValueAt(i, 3).toString();                    
                    String birthday = tbdulieu.getValueAt(i, 4).toString();
                    String sex = tbdulieu.getValueAt(i, 5).toString();
                    String cmnd = tbdulieu.getValueAt(i, 6).toString();
                    String address = tbdulieu.getValueAt(i, 7).toString();
                    String phone = tbdulieu.getValueAt(i, 8).toString();
                    String email = tbdulieu.getValueAt(i, 9).toString();
                    String id = tbdulieu.getValueAt(i, 10).toString();
                    dtm.addRow(new Object[] { new Boolean(false), login, name, companyname, birthday, sex, cmnd,
                            address, phone, email, id });
                }
            }
            for (int i = 0; i < tbdulieu.getRowCount(); i++) {
                while (tbdulieu.getRowCount() != dem) {
                    dtm.removeRow(0);
                }
            }
            txtcompanyname.setText("");
            txtloginname.setText("");
        } else {
            reloadtable();
        }
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        setUndecorated(true);
        lbcompanyname = new javax.swing.JLabel();
        txtloginname = new javax.swing.JTextField();
        txtname = new javax.swing.JTextField();
        txtcompanyname = new javax.swing.JTextField();
        txtage = new javax.swing.JTextField();
        txtcmnd = new javax.swing.JTextField();
        txtaddress = new javax.swing.JTextField();
        txtemail = new javax.swing.JTextField();
        cbbsex = new javax.swing.JComboBox();
        btbillpayment = new javax.swing.JButton();
        btreset = new javax.swing.JButton();
        btseach = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbdulieu = new javax.swing.JTable();
        btexit = new javax.swing.JButton();
        btview = new javax.swing.JButton();
        btedit = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        btinsert = new javax.swing.JButton();
        btregistry = new javax.swing.JButton();
        lbloginname = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setLocation(350, 150);
        Object colNames[] = { "", "LoginName", "Name", "CompanyName", "Birthday", "Sex", "Cmnd", "Address", "Phone",
                "Email", "" };
        Object[][] data = {};

        dtm = new DefaultTableModel(data, colNames);
        tbdulieu = new JTable(dtm);
        tbdulieu.getColumnModel().getColumn(0).setResizable(false);
        tbdulieu.getColumnModel().getColumn(1).setResizable(false);
        tbdulieu.getTableHeader().setReorderingAllowed(false);
        tbdulieu.getColumnModel().getColumn(0).setMinWidth(100);
        tbdulieu.getColumnModel().getColumn(9).setMinWidth(100);
        tbdulieu.getColumnModel().getColumn(10).setMaxWidth(0);
        tbdulieu.getColumnModel().getColumn(10).setMinWidth(0);
        tbdulieu.getColumnModel().getColumn(10).setWidth(0);

        try {
            Registry registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
            EtowInterface obj = (EtowInterface) registry.lookup(connectRMI.regis);

            List<GroupClass.AccountClass> x = obj.showlogin();

            for (GroupClass.AccountClass d : x) {
                int id = d.getId();
                String login = d.getLoginname();
                String name = d.getName();
                String companyname = d.getCompanyName();
                String birthday = ConverDateTime(d.getBirthday());
                String sex = d.getSex();
                String cmnd = d.getCmnd();
                String address = d.getAddress();
                String phone = d.getPhone();
                String email = d.getEmail();

                dtm.addRow(new Object[] { new Boolean(false), login, name, companyname, birthday, sex, cmnd, address,
                        phone, email, id });
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        TableColumn tc = tbdulieu.getColumnModel().getColumn(0);
        tc.setCellEditor(tbdulieu.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(tbdulieu.getDefaultRenderer(Boolean.class));
        tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));

        lbcompanyname.setText("Companyname");
        lbloginname.setText("LoginName");

        cbbsex.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "------", "Male", "Famale" }));

        btbillpayment.setText("Bill Payment");

        btreset.setText("Reset");

        btreset.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                txtloginname.setText("");
                txtname.setText("");
                txtcompanyname.setText("");
                txtage.setText("");
                txtaddress.setText("");
                txtemail.setText("");
                txtcmnd.setText("");
                cbbsex.setSelectedIndex(0);

            }
        });

        btseach.setText("Seach");
        btseach.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                SeachTable();

            }
        });

        jScrollPane1.setViewportView(tbdulieu);

        btexit.setText("Exit");

        btexit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                AdminControl ac = new AdminControl();
                ac.setVisible(true);
                setVisible(false);

            }
        });

        btview.setText("View Account");

        btview.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                AccountView av = new AccountView(null, true);
                av.setVisible(true);
            }
        });

        tbdulieu.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                e.consume();
                row = tbdulieu.getSelectedRow();
                click1 = tbdulieu.getValueAt(row, 1).toString();
                click2 = tbdulieu.getValueAt(row, 2).toString();
                click3 = tbdulieu.getValueAt(row, 3).toString();
                click4 = tbdulieu.getValueAt(row, 4).toString();
                click5 = tbdulieu.getValueAt(row, 5).toString();
                click6 = tbdulieu.getValueAt(row, 6).toString();
                click7 = tbdulieu.getValueAt(row, 7).toString();
                click8 = tbdulieu.getValueAt(row, 8).toString();
                click9 = tbdulieu.getValueAt(row, 9).toString();
                click10 = tbdulieu.getValueAt(row, 10).toString();

                a1 = click1;
                a2 = click2;
                a3 = click3;
                a4 = click4;
                a5 = click5;

                a6 = click6;
                a7 = click7;
                a8 = click8;
                a9 = click9;
                a10 = click10;

            }

        });
        btedit.setText("Edit Account");
        btedit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {

                EditAccount ea = new EditAccount(null, true);                
                ea.setCheckedit(a10);
                ea.setVisible(true);
                while (ea.isVisible() != true) {
                    if (ea.getCheckedit().equals("close")) {
                        reloadtable();
                        break;
                    }
                }
            }
        });

        btdelete.setText("Delete Account");
        btdelete.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                String result = "";
                int i = JOptionPane.showConfirmDialog(null, "Neu Ban Da Chac Chan Hay Chon Ok", null,
                        JOptionPane.YES_NO_OPTION);
                if (i == JOptionPane.YES_OPTION) {
                    EtowInterface obj = null;
                    Registry registry;
                    try {
                        registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
                        obj = (EtowInterface) registry.lookup(connectRMI.regis);
                        dem = 0;
                        for (int j = 0; j < tbdulieu.getRowCount(); j++) {
                            if (tbdulieu.getValueAt(j, 0).toString() == "true") {
                                try {
                                    dem += 1;
                                    result = obj.DeleteAccount(tbdulieu.getValueAt(j, 10).toString());
                                    if (result != "Ok") {
                                        System.out.println(result);
                                        JOptionPane.showMessageDialog(null, "This Account "+ tbdulieu.getValueAt(j, 2).toString() + " using Unit in Town");
                                    }
                                    
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                        }                       
                        reloadtable();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        btinsert.setText("Insert Account");
        btinsert.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                InsertAccount ia = new InsertAccount(null, true);
                ia.setCheckvisable("ok");
                ia.setVisible(true);
                while (ia.isVisible() != true) {
                    if (ia.getCheckvisable().equals("close")) {
                        reloadtable();
                        break;
                    }
                }
            }
        });
        btregistry.setText("Registry Town");
        btregistry.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                for (int j = 0 ; j < tbdulieu.getRowCount();j++)
                {               
                        if(tbdulieu.getValueAt(j, 0).toString() == "true")
                        {       
                                TownFree tow = new TownFree(null,true);
                                tow.setAccountId(a10);                                
                                tow.setVisible(true);
                        }                                                                                                                                   
                }              
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addGroup(
                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addContainerGap()
                                                                .addComponent(jScrollPane1,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE, 666,
                                                                        Short.MAX_VALUE))
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addGap(39, 39, 39)
                                                                .addComponent(btregistry)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(btinsert)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(btedit)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(btdelete)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(btview)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(btexit,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 68,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addContainerGap())
                .addGroup(
                        layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(
                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addComponent(lbcompanyname)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(btseach)
                                                                                .addComponent(
                                                                                        txtcompanyname,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                        168,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addComponent(lbloginname)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        Short.MAX_VALUE)
                                                                .addComponent(txtloginname,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 169,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addContainerGap(432, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup()
                        .addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(txtloginname, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lbloginname))
                        .addGap(18, 18, 18)
                        .addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(lbcompanyname)
                                        .addComponent(txtcompanyname, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btseach)
                        .addGap(3, 3, 3)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 163,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btview).addComponent(btdelete).addComponent(btexit)
                                        .addComponent(btedit).addComponent(btinsert).addComponent(btregistry))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Account dialog = new Account(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);

            }
        });
    }

    class MyItemListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
            Object source = e.getSource();
            if (source instanceof AbstractButton == false)
                return;
            boolean checked = e.getStateChange() == ItemEvent.SELECTED;
            for (int x = 0, y = tbdulieu.getRowCount(); x < y; x++) {
                tbdulieu.setValueAt(new Boolean(checked), x, 0);
            }
        }
    }

    public static String getA1() {
        return a1;
    }

    public static String getA2() {
        return a2;
    }

    public static String getA3() {
        return a3;
    }

    public static String getA4() {
        return a4;
    }

    public static String getA5() {
        return a5;
    }

    public static String getA6() {
        return a6;
    }

    public static String getA7() {
        return a7;
    }

    public static String getA8() {
        return a8;
    }

    public static String getA9() {
        return a9;
    }

    public static String getA10() {
        return a10;
    }

    public static void setA10(String a10) {
        Account.a10 = a10;
    }

    public String ConverDateTime(String oldday)
    {
        String newday = null;
        try
        {
            
            SimpleDateFormat formatter, FORMATTER;     
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");  
            String oldDate = oldday;  
            Date date;
            date = formatter.parse(oldDate.substring(0, 21));
            FORMATTER = new SimpleDateFormat("dd/MM/yyyy");     
            newday = FORMATTER.format(date);
        }catch(ParseException e)
        {
            e.printStackTrace();
        }     
        
        return newday;
    }
    public void reloadtable() {

        while (tbdulieu.getRowCount() != 0) {
            dtm.removeRow(0);
        }

        try {
            Registry registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
            EtowInterface obj = (EtowInterface) registry.lookup(connectRMI.regis);

            List<GroupClass.AccountClass> x = obj.showlogin();

            for (GroupClass.AccountClass d : x) {
                int id = d.getId();
                String login = d.getLoginname();
                String name = d.getName();
                String companyname = d.getCompanyName();
                String birthday = ConverDateTime(d.getBirthday());
                String sex = d.getSex();
                String cmnd = d.getCmnd();
                String address = d.getAddress();
                String phone = d.getPhone();
                String email = d.getEmail();

                dtm.addRow(new Object[] { new Boolean(false), login, name, companyname, birthday, sex, cmnd, address,
                        phone, email, id });
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
